package com.jie.component.validation.validator.impl;

import cn.hutool.core.util.StrUtil;
import com.jie.common.util.RegexUtil;
import com.jie.component.validation.annotion.Password;
import com.jie.component.validation.validator.ConstraintValidator;

/**
 * @author jie
 * @version 1.0 2025-02-13
 */
public class PasswordValidator implements ConstraintValidator<Password> {

    @Override
    public boolean isValid(Object value, Password annotation) {
        if (!annotation.required() && StrUtil.isBlank(value.toString())) {
            return true;
        }

        if (annotation.required() && StrUtil.isBlank(value.toString())) {
            return false;
        }

        String password = value.toString();
        return RegexUtil.isMatch(annotation.regex(), password);
    }

    @Override
    public String getMessage(Password annotation) {
        if (StrUtil.isBlank(annotation.message())) {
            return "密码格式错误，正确格式: " + annotation.regex();
        }
        return annotation.message();
    }
}
